package ua.org.extjsbuilder.parser;

import java.io.IOException;
import java.io.InputStream;

import junit.framework.TestCase;

public class JSParserTestCase extends TestCase {
	private static final String MOCK_PKG = "ua/org/extjsbuilder/parser/mock/";
	
	public void testParser() throws IOException {
		parseSuccess("test1.js");
		parseFailure("test2.js");
		parseFailure("test3.js");
		parseFailure("test4.js");
		parseSuccess("test5.js");
		parseFailure("test6.js");
	}
	
	public void testPerformance() throws IOException{
		fail("Not implemented now");
		long time = System.currentTimeMillis();
		parseSuccess("test10.js");
		time = System.currentTimeMillis()-time;
		assertTrue("Actual time is "+time+" ms (but 2sec expected)",
				time<2000);
	}

	private void parseFailure(String resource) throws IOException {
		try{
			parse(getStream(resource));
			fail("This resource should fail when parsing");
		}
		catch(JSParseException ex){
			//print traces in stdout for analysis
			ex.printStackTrace();
		}
	}

	private void parse(InputStream stream) throws IOException {
		assertNotNull(stream);
		new JSParser(stream).parse(new TestErrorHandler());
	}

	private InputStream getStream(String resource) {
		return getClass().getClassLoader()
			.getResourceAsStream(MOCK_PKG+resource);
	}

	private void parseSuccess(String resource) throws IOException {
		parse(getStream(resource));
	}
	
	private static class TestErrorHandler implements JSErrorHandler {

		public void clear() {}

		public void error(String message, int line) {
			throw new JSParseException(message);
		}

		public void warn(String message, int line) {}
	}
}
